package top.yuyufeng.mbuy.utils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 类拷贝转化工具类
 * @Author:俞育峰
 * @Date:2019/7/22 10:38
 */
public class PageInfoUtil {
    /**
     * PageInfo浅拷贝
     *
     * @param pageInfoPO
     * @param dClass
     * @param <P>
     * @param <D>
     * @return
     */
    public static <P, D> PageInfo<D> pageInfo2PageInfoDTO(PageInfo<P> pageInfoPO, Class<D> dClass) {
        Page<D> page = new Page<>(pageInfoPO.getPageNum(), pageInfoPO.getPageSize());
        page.setTotal(pageInfoPO.getTotal());
        if (pageInfoPO.getList() != null) {
            for (P p : pageInfoPO.getList()) {
                D d = null;
                try {
                    d = dClass.newInstance();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                BeanUtils.copyProperties(p, d);
                page.add(d);
            }
        }

        return new PageInfo<>(page);
    }


    /**
     * List对象浅拷贝
     *
     * @param list
     * @param dClass
     * @param <P>
     * @param <D>
     * @return
     */
    public static <P, D> List<D> transPOList2DTOList(List<P> list, Class<D> dClass) {
        List<D> result = new ArrayList<>();
        if (list != null) {
            for (P p : list) {
                if(p == null){
                    continue;
                }
                D d = null;
                try {
                    d = dClass.newInstance();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                BeanUtils.copyProperties(p, d);
                result.add(d);
            }
        }
        return result;
    }

}
